package org.ykhl.mq.dispatcher.rule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.ykhl.mq.util.HttpUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class DispatchService {
    private static final Logger LOG = LoggerFactory.getLogger(DispatchService.class);
    private final String apiUrl;
    private HttpUtil httpUtil = new HttpUtil();


    public DispatchService(String apiUrl) {
        Objects.requireNonNull(apiUrl, "ApiUrl can't be null");
        this.apiUrl = apiUrl;
    }

    public Map getTransformInfo(String resid,String appid,String version){
        Map<String, Object> result =new HashMap<>();
        String url = apiUrl + "/api/dispatch/transformInfo";
        LOG.debug("getTransformInfo  - " + url + "?resid=" + resid + "&appid=" +appid + "&version=" +version);

        Map<String, Object> parameters =new HashMap<>();
        parameters.put("resid",resid);
        parameters.put("appid",appid);
        parameters.put("version",version);
        String  resp= "";
        try {
              resp= httpUtil.post(url,parameters);
            JSONObject object = JSON.parseObject(resp);

            if(object.containsKey("Code")){//表示有异常
                result.put("Code",object.getString("Code"));
            }else if(object.containsKey("isTransform")){
                String isTransform = object.getString("isTransform");
                result.put("isTransform",isTransform);
                if(isTransform.equals("true")) {//表示要进行转换
                    result.put("secretKey",object.getString("secretKey"));
                    result.put("ruleFileContent",object.getString("ruleFileContent"));
                }else if(isTransform.equals("false")){
                    result.put("secretKey","");
                    result.put("ruleFileContent","");
                    LOG.debug("getTransformInfo is false&&&&&&" + resp);
                }else{
                    LOG.error("getTransformInfo is error--" + resp);
                }
            }
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            LOG.error("getTransformInfo is Exception error--" + sw);
            LOG.error("getTransformInfo is Exception error-- httpUtil:" + httpUtil + " ,resp:" + resp);

        }
        return result;
    }

    /**
     * 根据请求来源AppServer的id, 请求的服务ID(fid), 请求设备的特征码, 返回应该转发请求的目的医院id
     *
     * @param appserverId 来源AppServer的id
     * @param dataType 响应的消息数据类型
     * @return 转发该请求的目的医院id, null则说明规则没有配置在数据库中, 或设备在黑名单中
     */
    public String getHospitalIdForRequest(String appserverId, String dataType) {

        String url = apiUrl + "/api/dispatch/getHosIdForRequest";
        LOG.debug("getHospitalIdForRequest - " + url + "?appid=" + appserverId + "&resid=" +dataType);

        Map<String, Object> parameters =new HashMap<>();
        parameters.put("resid",dataType);
        parameters.put("appid",appserverId);
        try {
            String  resp= httpUtil.post(url,parameters);
            JSONObject object = JSON.parseObject(resp);
            if(object.containsKey("content")) {
                String hosId = object.getString("content");
                return hosId;
            }else{
                LOG.error("getHospitalIdForRequest is error--" + resp);
            }
        }catch (Exception e){
            LOG.error("getHospitalIdForRequest is Exception error--" + e.getMessage());
        }
        return "";
    }


    /**
     * 获取规则文件的内容（.xsl内容）
     * @return
     * @throws IOException
     */
    public String getRuleFileContent(String xslPath){
        String url = apiUrl + "/api/dispatch/getRuleFileContent";
        LOG.debug("getRuleFileContent - " + url + "?path=" + xslPath);

        Map<String, Object> parameters =new HashMap<>();
        parameters.put("path",xslPath);
        try {
            String  resp= httpUtil.post(url,parameters);
            JSONObject object = JSON.parseObject(resp);
            if(object.containsKey("content")) {
                String ruleFile = object.getString("content");
                LOG.debug("getRuleFileContent size - " +ruleFile.length());
                return ruleFile;
            }else{
                LOG.error("getRuleFileContent is error--" + resp);
            }
        }catch (Exception e){
            LOG.error("getRuleFileContent is Exception error--" + e.getMessage());
        }
            return "";
    }
}